/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 UJF.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

package org.osami.gateway.sensor.proxy;

import static javax.servlet.http.HttpServletResponse.SC_NOT_ACCEPTABLE;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import static org.osami.gateway.tools.JsonRestTools.CONTENT_TYPE_JSON;
import static org.osami.gateway.tools.JsonRestTools.stringToJSONObjects;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.osami.gateway.tools.JsonRestTools;

public class SensorNodeServlet extends HttpServlet {

    private final SensorNodeProxy senseNode;

    public SensorNodeServlet(SensorNodeProxy pSenseNode) {
        super();
        senseNode = pSenseNode;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPut(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String contenttype = req.getContentType();

        // Set content type to JSON if null
        if (contenttype == null) {
            contenttype = CONTENT_TYPE_JSON;
        }

        try {

            // Handle the content as a JSONARRAY or a JSON Object and notify the
            // proxy with the data.
            if (contenttype.equals(CONTENT_TYPE_JSON)) {
                String content = JsonRestTools.read(req.getInputStream());

                // Convert the JSON String to a Collection of JSONObject and
                // notify the proxy.
                senseNode.processData(stringToJSONObjects(content));

                resp.setStatus(SC_NO_CONTENT);
            } else {
                resp.sendError(SC_NOT_ACCEPTABLE);
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}
